import {
    request,
    AbstractBookCrawler,
    BasicBook,
    SearchBookResult,
    Book,
    BasicChapter,
    BookCrawlerTest,
    BookSource,
    htmlToString,
} from "../../common/common_node.js";

class BookCrawler extends AbstractBookCrawler {

    async searchBook(keyword, pageNum) {
        function getBoolList($) {
            const bookArr = [];
            const liArr = $("#main ul li");
            liArr.each(function (index, elem) {
                if (index === 0) {
                    return;
                }
                let tds = $(elem).find("span");
                let nameAndPath = tds.eq(1).find("a");
                bookArr.push(new BasicBook({
                    name: nameAndPath.text(), author: tds.eq(3).text(), path: nameAndPath.attr("href"),
                }));
            })
            return bookArr;
        }

        let url = `${this.source.searchBaseUrl}/cse/search?q=${encodeURIComponent(keyword)}`;
        const $ = await (await request(url)).doc();
        const bookArr = getBoolList($);

        return new SearchBookResult({
            pageNum: 1, pages: 1, keyword: keyword, bookList: bookArr
        });
    }

    async bookDetails(path) {
        const $ = await (await request(this.source.bookBaseUrl + path)).doc();

        return new Book({
            name: $("meta[property='og:novel:book_name']").attr('content'),
            author: $("meta[property='og:novel:author']").attr('content'),
            path: path,
            intro: htmlToString($("meta[property='og:description']").attr('content')),
            coverUrl: $("meta[property='og:image']").attr('content'),
            type: $("meta[property='og:novel:category']").attr('content'),
        });
    }

    async bookCatalog(path) {
        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        const chapters = $('#list dt:eq(1)').nextAll();
        let catalog = [];
        chapters.each(function (i, elem) {
            const item = $(elem).find('a');
            catalog.push(new BasicChapter({
                index: i,
                title: item.text(),
                path: item.attr("href")
            }));
        });
        return catalog;
    }

    async chapterContent(path) {
        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        let content = $("#content").html();
        return htmlToString(content);
    }
}

const source = {
    "id": "free_book_js/15",
    "name": "影书",
    "portalUrl": "https://www.yingsx.com",
    "searchBaseUrl": "https://www.yingsx.com",
    "bookBaseUrl": "https://www.yingsx.com",
    "active": true
};

await new BookCrawlerTest(new BookCrawler(BookSource.createTestBookSource(source)), {
    enableSearch: true, keyword: "重生",
}).run();